package cn.lingyangwl.agile.system.manager;

import cn.lingyangwl.agile.common.core.config.GlobalProperties;
import cn.lingyangwl.agile.system.mapper.SysConfigMapper;
import cn.lingyangwl.agile.system.model.entity.SysConfig;
import cn.lingyangwl.framework.mybatis.mate.annotations.FieldUniqueCheck;
import cn.lingyangwl.framework.mybatis.mate.enums.OperationTypeEnum;
import cn.lingyangwl.framework.tool.core.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Component
public class SysConfigManager
        extends ServiceImpl<SysConfigMapper, SysConfig> implements IService<SysConfig> {
    @Resource
    private SysConfigMapper configMapper;
    @Resource
    private GlobalProperties globalProperties;
    
    @FieldUniqueCheck(type = OperationTypeEnum.UPDATE)
    public boolean updateConfig(SysConfig po) {
        return this.updateById(po);
    }

    @FieldUniqueCheck(type = OperationTypeEnum.SAVE)
    public boolean saveConfig(SysConfig po) {
        return this.save(po);
    }

    public SysConfig getByConfigKey(String configKey) {
        if (StringUtils.isEmpty(configKey)) {
            return null;
        }
        LambdaQueryWrapper<SysConfig> wrapper = SysConfig.lqw().eq(SysConfig::getConfigKey, configKey);
        SysConfig config = configMapper.selectList(wrapper).stream().findFirst().orElse(null);
        if (Objects.isNull(config)) {
            return null;
        }
        SysConfig copedConfig = new SysConfig();
        BeanUtils.copyProperties(config, copedConfig);
        return copedConfig;
    }
}
